<?php
include_once APPPATH . 'libraries/aliyun-php-sdk-core/Config.php';
include_once APPPATH . 'libraries/aliyun-oss-php-sdk-2.2.4/autoload.php';
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| 朋友圈模型
|@author khj
|--------------------------------------------------------------------------
*/
class FriendsCircle extends MY_Controller {

	/**
	 * 朋友圈买家秀模型
	 * @var ConsumerFriendsCircleModel
	 */
	public $mFriends;
    /**
     * 朋友圈卖家秀模型
     * @var MerchantFriendsCircleModel
     */
    public $mMerFriends;
	
	public function __construct(){
		parent::__construct();

		$this->loadModel('ConsumerFriendsCircleModel', 'mFriends', 'consumer');

	}
    /**
     * 他的动态
     */
    public function index(){
        error_reporting(E_ALL^E_WARNING^E_NOTICE);//显示除去E_WARNING E_NOTICE 之外的所有错误信息
        $this->loadModel('ConsumerFindModel', 'mFind', 'consumer');
        //表单验证
        $vConf = array(
            array('page', '页码', 'required|is_natural_no_zero'),
            array('id', '他的id', 'required|is_natural_no_zero'),
            array('type', '类型', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf);

        $page = post('page');
        $relationId = post('id');
        $type = (int)post('type');
        $type = $type == 0 ? 1 : $type;
        $tA = $this->mFriends->appGetFriendsCircleList($page, $type, $this->userId, $relationId);
        foreach ($tA['list'] as $k=>$v){
            if($v['video']){
                $result = $this->showVideo($v['video']);
                if(!$result['status']){
                    $this->appReturn(0, $result['message']);
                }
                $tA['list'][$k]['video'] = $result['data']['video'];
                $tA['list'][$k]['coverUrl'] = $result['data']['CoverURL'];
            }
        }
        if ($type == 1){
            $info = $this->mUser->getInfo($relationId);
        }else{
            $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            $info = $this->mMerchant->getInfo($relationId, 0, true);
        }

        $data = array(
            'list' => $tA['list'],
            'friends_count' => $tA['total'],
            'find_count' => $this->mFind->getFindTotal($relationId),
            'userMobile' => substr($info['mobile'], 0, 3).'****'.substr($info['mobile'],-4)
        );

        $this->appReturn(1, '', $data);
    }
	/**
     * 添加朋友圈动态
     */
	public function addFriendsCircle(){
        //表单验证
//        $vConf = array(
//            array('latitude', '坐标', 'required'),
//            array('longitude', '坐标', 'required'),
//            array('address', '地址', 'required'),
//
//        );
//        $this->formDataValidation($vConf);

        $content = trim(post('content'));
        if(!$content && !$_FILES)$this->appReturn(0,'请发布动态');

        //上传图片/视频
        $img = array();
        $yun_status = 2;
        $video = '';
        $path = 'uploads/'.$this->port.'/'.$this->userId.'/friends';
        if($_FILES){
            if(count($_FILES) > 6 )$this->appReturn(0,'上传图片最多六张');
            foreach ($_FILES as $k=>$v){
                if($k != 'video'){
                    $filename = uniqid();
                    $tS = imageUpload($path,$k, $filename, true);
                    if( ! $tS['status']){
                        $this->appReturn(0,'上传失败');
                    }
                    $img[] = $tS['data'];
                }
                if($k == 'video'){
                    $tA = $this->addVideo($_FILES['video']);
                    if( ! $tA['status']){
                        $this->appReturn(0,'上传失败');
                    }
                    $yun_status = 1;
                    $video = $tA['data'];
                }
            }
        }
        if(!$content && !$video && !$img){
            $this->appReturn(0,'请发布动态内容');
        }

        $data = array(
            'consumer_id' => $this->userId,
            'video' => $video,
            'image' => json_encode($img),
            'address' => trim(post('address')),
            'content' => base64_encode($content),
            'latitude' => trim(post('latitude')),
            'longitude' => trim(post('longitude')),
            'browse_number' => 0,
            'status' => 1,
            'yun_status' => $yun_status,
            'addtime' => time(),
        );

        //保存
        if(!($this->mFriends->save($data))){
            $this->appReturn(0, '发布失败');
        }

        $this->appReturn(1, '发布成功,审核中~');
    }

    /**
     * 朋友圈列表
     * type 1买家秀 2卖家秀
     */
    public function getFriendsCircleList(){
        error_reporting(E_ALL^E_WARNING^E_NOTICE);//显示除去E_WARNING E_NOTICE 之外的所有错误信息
        //表单验证
        $vConf = array(
            array('page', '页码', 'required|is_natural_no_zero'),
            array('type', '类型', 'required|in_list[1,2]'),

        );
        $this->formDataValidation($vConf);

        $page = post('page');
        $type = post('type');

        $tA = $this->mFriends->appGetFriendsCircleList($page, $type, $this->userId);

	    foreach ($tA['list'] as $k=>$v){

            if($v['video']){
                $result = $this->showVideo($v['video']);
                if(!$result['status']){
                    $this->appReturn(0, $result['message']);
                }
                $tA['list'][$k]['video'] = $result['data']['video'];
                $tA['list'][$k]['coverUrl'] = $result['data']['CoverURL'];
            }
        }

        $this->appReturn(1, '', $tA);
    }

    /**
     * 获取动态详情
     */
    public function friendsCircleDetail(){
        //表单验证
        $vConf = array(
            array('fid', '动态id', 'required|is_natural_no_zero'),
            array('type', '类型', 'required|in_list[1,2]'),

        );
        $this->formDataValidation($vConf);

        $fid = post('fid');
        $type = post('type');

        //验证动态是否存在
        $info = $this->mFriends->getInfo($fid, $type, 0, false, $this->userId);
        if(!$info){
            $this->appReturn(0, '动态不存在');
        }
        //获取视频路径
        if($info['video']){
            $result = $this->showVideo($info['video']);
            if(!$result['status']){
                $this->appReturn(0, $result['message']);
            }

            $info['video'] = $result['data']['video'];
            $info['coverUrl'] = $result['data']['CoverURL'];
        }
        //动态评论记录
        $comment = $this->mFriends->getAllComments($fid, $type);
        $info['commentList'] = $comment;
        //动态点赞记录
        $praise = $this->mFriends->getAllPraise($fid, $type, $limit = 12);
        $info['praiseList'] = $praise;
        //增加浏览量
        if($type == 1){
            if ( ! $this->mFriends->save(array('browse_number'=>$info['browse_number'] + 1),$fid)){
                $this->appReturn(0,'浏览失败');
            }
        }

        if($type == 2){
            if ( ! $this->mMerFriends->save(array('browse_number'=>$info['browse_number'] + 1),$fid)){
                $this->appReturn(0,'浏览失败');
            }
        }

        $this->appReturn(1, '', $info);
    }

    /**
     * 朋友圈点赞
     */
    public function praise(){
        //表单验证
        $vConf = array(
            array('fid', '动态id', 'required|is_natural_no_zero'),
            array('type', '类型', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf);

        $fid = post('fid');
        $type = post('type');

        //验证动态是否存在
        $info = $this->mFriends->getInfo($fid, $type, 0, true);
        if(!$info){
            $this->appReturn(0, '动态不存在');
        }

        //验证点赞是否存在
        $isExist = $this->mFriends->praiseIsExist($fid, $this->userId, $type);
        if($isExist){
            //取消点赞
            if(!($this->mFriends->deletePraise($fid, $this->userId, $type))){
                $this->appReturn(0, '取消失败');
            }
            $this->appReturn(1, '取消成功');
        }
        //点赞
        $data = array(
            'fid' => $fid,
            'type' => $type,
            'user_type' => 1,
            'consumer_id' => $this->userId,
            'addtime' => time()
        );
        if(!($this->mFriends->savePraise($data))){
            $this->appReturn(0, '点赞失败');
        }

        $this->appReturn(1, '点赞成功');
    }

    /**
     * 朋友圈评论
     */
    public function addcomment(){
        //表单验证
        $vConf = array(
            array('fid', '动态id', 'required|is_natural_no_zero'),
            array('type', '类型', 'required|in_list[1,2]'),
            array('content', '评论内容', 'required'),
        );
        $this->formDataValidation($vConf);

        $fid = post('fid');
        $type = post('type');

        //验证动态是否存在
        $info = $this->mFriends->getInfo($fid, $type, 0,true);
        if(!$info){
            $this->appReturn(0, '动态不存在');
        }

        $data = array(
            'fid' => $fid,
            'consumer_id' => $this->userId,
            'type' => $type,
            'user_type' => 1,
            'content' => base64_encode(trim(post('content'))),
            'addtime' => time(),
        );
        if(!($this->mFriends->saveComment($data))){
            $this->appReturn(0, '评论失败');
        }

        $this->appReturn(1, '评论成功');
    }

    /**
     * 回复评论
     */
    public function replyComment(){
        //表单验证
        $vConf = array(
            array('comment_id', '评论id', 'required|is_natural_no_zero'),
            array('type', '类型', 'required|in_list[1,2]'),
            array('reply', '回复内容', 'required'),
            array('parent_name', '回复对象昵称', 'required'),
        );
        $this->formDataValidation($vConf);

        $comment_id = post('comment_id');
        $type = post('type');
        $reply = trim(post('reply'));
        $parent_name = trim(post('parent_name'));
        //验证评论是否存在
        $commentInfo = $this->mFriends->getCommentInfo($comment_id);
        if(!$commentInfo){
            $this->appReturn(0, '评论信息不存在');
        }
        //验证动态是否存在
        $info = $this->mFriends->getInfo($commentInfo['fid'], $type, 0, true);
        if(!$info){
            $this->appReturn(0, '动态不存在');
        }
        $data = array(
            'fid' => $commentInfo['fid'],
            'consumer_id' => $this->userId,
            'type' => $type,
            'user_type' => 1,
            'parent_name' => $parent_name,
            'content' => base64_encode($reply),
            'addtime' => time(),
        );
        if(!($this->mFriends->saveComment($data))){
            $this->appReturn(0, '回复失败');
        }

        $this->appReturn(1, '回复成功');
    }

    /**
     * 我的动态
     */
    public function myFriendsCircle(){
        $this->loadModel('ConsumerFindModel', 'mFind', 'consumer');
        //表单验证
        $vConf = array(
            array('page', '页码', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $page = post('page');

        $tA = $this->mFriends->appGetFriendsCircleList($page, 1, $this->userId, $this->userId);
        foreach ($tA['list'] as $k=>$v){
            if($v['video']){
                $result = $this->showVideo($v['video']);
                if(!$result['status']){
                    $this->appReturn(0, $result['message']);
                }
                $tA['list'][$k]['video'] = $result['data']['video'];
                $tA['list'][$k]['coverUrl'] = $result['data']['CoverURL'];
            }
        }
        $data = array(
            'list' => $tA['list'],
            'friends_count' => $tA['total'],
            'find_count' => $this->mFind->getFindTotal($this->userId),
        );
        $this->appReturn(1, '', $data);
    }

    /**
     * 删除我的动态
     */
    public function deleteFriendsCircle(){
        //表单验证
        $vConf = array(
            array('fid', '动态id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $fid = post('fid');

        //验证动态是否存在
        $info = $this->mFriends->getInfo($fid, 1, $this->userId, true);
        if(!$info){
            $this->appReturn(0, '动态不存在');
        }

        if(!($this->mFriends->deleteCircle($fid, $this->userId))){
            $this->appReturn(0, '删除失败');
        }

        $this->appReturn(1, '删除成功');
    }

	/*
	 * -----------------------------------------视频上传--------------------------------------------------
	 */

    /**
     * 视频上传
     */
    public function addVideo($file){
        $accessKeyId = 'LTAI9YmG9Xp8NgiQ';                    // 您的AccessKeyId
        $accessKeySecret = 'CZsLD8ahO4fa7axKTxjlsICO5mpkwA';            // 您的AccessKeySecret
        $localFile = $file['tmp_name'];   // 需要上传到VOD的本地视频文件的完整路径

        try {
            // 初始化VOD客户端并获取上传地址和凭证
            $vodClient = $this->init_vod_client($accessKeyId, $accessKeySecret);
            $createRes = $this->create_upload_video($vodClient,$file);
            // 执行成功会返回VideoId、UploadAddress和UploadAuth
            $videoId = $createRes->VideoId;
            $uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
            $uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);
            // 使用UploadAuth和UploadAddress初始化OSS客户端
            $ossClient = $this->init_oss_client($uploadAuth, $uploadAddress);
            // 上传文件，注意是同步上传会阻塞等待，耗时与文件大小和网络上行带宽有关
            $result = $this->upload_local_file($ossClient, $uploadAddress, $localFile);

            return array('status' => 1,'message' =>'', 'data' => $videoId);

        } catch (Exception $e) {
            return array('status' => 0,'message' =>'Failed, ErrorMessage:'.$e->getMessage(), 'data' => 0);
        }
    }

    /**
     * 视频播放
     */
    public function showVideo($videoId){
        $accessKeyId = 'LTAI9YmG9Xp8NgiQ';                    // 您的AccessKeyId
        $accessKeySecret = 'CZsLD8ahO4fa7axKTxjlsICO5mpkwA';            // 您的AccessKeySecret
        if(!$videoId){
            return array('status' => 0,'message' =>'视频地址为空', 'data' => '');
        }
        try {
            // 初始化VOD客户端并获取上传地址和凭证
            $vodClient = $this->init_vod_client($accessKeyId, $accessKeySecret);
            $playInfo = $this->get_play_info($vodClient, $videoId);
            $playList = $playInfo->PlayInfoList->PlayInfo;
            $url = $playList[1]->PlayURL;

            return array('status' => 1,'message' =>'', 'data' => array('video' => $url, 'CoverURL'=>$playInfo->VideoBase->CoverURL));

        } catch (Exception $e) {

            return array('status' => 0,'message' =>'Failed, ErrorMessage:'.$e->getMessage(), 'data' => '');
        }
    }

    /**
     * 获取播放地址
     */
    private function get_play_info($client, $videoId) {
        $request = new vod\GetPlayInfoRequest();
        $request->setVideoId($videoId);
        $request->setAuthTimeout(3600*24);    // 播放地址过期时间（只有开启了URL鉴权才生效），默认为3600秒，支持设置最小值为3600秒
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    //使用上传凭证和地址初始化OSS客户端（注意需要先Base64解码并Json Decode再传入）
    private function init_oss_client($uploadAuth, $uploadAddress) {
        $ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
            false, $uploadAuth['SecurityToken']);
        $ossClient->setTimeout(86400*7);    // 设置请求超时时间，单位秒，默认是5184000秒, 建议不要设置太小，如果上传文件很大，消耗的时间会比较长
        $ossClient->setConnectTimeout(10);  // 设置连接超时时间，单位秒，默认是10秒
        return $ossClient;
    }

    /**
     * 获取视频上传凭证和地址
     * @param $client
     * @param $regionId
     * @return mixed
     */
    private function create_upload_video($client,$file)
    {

        $request = new vod\CreateUploadVideoRequest();

        //视频源文件标题(必选)
        $request->setTitle('视频上传测试');
        //视频源文件名称，必须包含扩展名(必选)
        $request->setFileName($file['name']);
        //视频源文件字节数(可选)
        $request->setFileSize($file['size']);
        //视频源文件描述(可选)
        $request->setDescription("视频上传测试");
        //自定义视频封面URL地址(可选)
        $request->setCoverURL('');
        //上传所在区域IP地址(可选)
        $request->setIP("127.0.0.1");
        //视频标签，多个用逗号分隔(可选)
        $request->setTags("");
        //视频分类ID(可选)
        $request->setCateId(988712795);
        $response = $client->getAcsResponse($request);
        return $response;
    }

    private function init_vod_client($accessKeyId, $accessKeySecret) {
        $regionId = 'cn-shanghai';     // 点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
        $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
        return new DefaultAcsClient($profile);
    }

    private function upload_local_file($ossClient, $uploadAddress, $localFile) {
        return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
    }

}
	